//
//  WLHomeViewController.m
//  WanLian
//
//  Created by muzhuang on 2018/8/30.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLHomeViewController.h"
#import "WLCloudController.h"
#import "WLloginController.h"
#import "SDCycleScrollView.h"
#import "WLBannerModel.h"
#import "WLWebViewController.h"
#import "WLMyScoreProfitController.h"
#import "UITabBar+WLTabbarBadge.h"
#import "WLMsgModel.h"
#import "WLMessageDetailController.h"
#import "NSString+Ext.h"
#import "WLRoutersModel.h"
#import "WLRouterBingFlowController.h"
#import "WLVersionUpdateView.h"
#import "WLDownLoadCenter.h"
#import "WLFileUpDownLoadModel.h"

//#import "WLRouterBingFlowController.h"

@interface WLHomeViewController ()<SDCycleScrollViewDelegate>//,RouterSocketDelegate>
{
//    SDCycleScrollView *cycleADView;
    
//    UIImageView *ivNotice;
//    UILabel *labNotice;
    
    UILabel *labYesProfit;
    UILabel *labPhotoStorage;
    UILabel *labVideoStorage;
//    UILabel *labAudioStorage;
    UILabel *labFreeStorage;
    
    BOOL isMaskOnShow;
}

@property (nonatomic, strong) UIScrollView  *homeScroller;
@property (nonatomic, copy) NSArray     *bannerLists;
@property (nonatomic, copy) NSDictionary    *dictStorage;

@property (nonatomic, strong) SDCycleScrollView  *cycleADView;
@property (nonatomic, strong) UIImageView  *ivNotice;
@property (nonatomic, strong) UILabel  *labNotice;
@property (nonatomic, strong) WLMsgModel *noticeModel;

@end

@implementation WLHomeViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([[WLUseManager shareUser] routerModel]) {
        [self connectToServer];
    }
}
- (void)connectToServer {
    if ([[WLUseManager shareUser] isLogin])
    {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSInteger guideIndex = [userDefaults integerForKey:@"maskGuideIndex"];
        if (guideIndex<1)
        {
            if (!isMaskOnShow) {
                isMaskOnShow = YES;
                [self showGuideMaskView];
            }
        }
        WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
        if (socketManager.routerSocket.isConnected)
        {
            if (socketManager.isRegistered==NO) {
                [socketManager routerSocketRegister];
            }
        }
        else
        {
            [socketManager connectServerHost];
            //            [socketManager routerSocketRegister];
        }
    }
}
- (void)hasLoadedRouterInfo {
    [self connectToServer];
    [self reqCloudstorage];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kLoadedRouterInfo object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kRefreshLoacalMessageNofication object:nil];
}
- (void)checkVersion {
    
    NSDictionary *paramsp = @{@"ckey":@"APP_VERSION_IOS"};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"config/getconfigbykey" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        NSString *newstVer = successDict[@"object"][@"versionCode"];
        NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        if ([newstVer compare:curVersion] == NSOrderedDescending) {
            WLVersionUpdateView *updateView = [[WLVersionUpdateView alloc] initWithInfo:successDict[@"object"]];
            [updateView show];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:self.view];
}
-(void)refreshLoacalMessage {
    [self reqUnreadMsgCount];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkVersion];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hasLoadedRouterInfo) name:kLoadedRouterInfo object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshLoacalMessage) name:kRefreshLoacalMessageNofication object:nil];
    
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
//    WLLog(@"%@",[UIFont familyNames]);
//    for (NSString *fontFamilyName in [UIFont familyNames]) {
//        NSLog(@"family: '%@'", fontFamilyName);
//        for (NSString *fontName in [UIFont fontNamesForFamilyName:fontFamilyName]) {
//            NSLog(@"\tfont:'%@'", fontName);
//        }
//        NSLog(@"--------------");
//    }
    //PingFangSC-Medium
    //'PingFangSC-Regular'
    
    _homeScroller = [[UIScrollView alloc] init];
//    _homeScroller.contentSize = CGSizeMake(WIDTH_SCREEN_WIDTH,HPX(1861));
//    _homeScroller.delegate = self;
    _homeScroller.showsVerticalScrollIndicator = NO;
    _homeScroller.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_homeScroller];
    
    WLWkSelf
    [_homeScroller mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(weakSelf.view);
        make.left.right.bottom.equalTo(weakSelf.view);
        make.top.equalTo(weakSelf.view.mas_top).offset(WL_Top);
    }];
    
    _homeScroller.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        [weakSelf refreshInfomation];
    }];
    
    [self setupUI];
    
    [self reqBannerList];
    
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLoginedToRefresh) name:kNOTIFICATION_LOGINED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routerChangeToRefresh) name:kNOTIFICATION_CHANGED object:nil];
#warning
    if (![[WLUseManager shareUser] isLogin])
    {
        WLloginController *loginController = [[WLloginController alloc] init];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:loginController] animated: NO completion:nil];
        return;
    }
    
    //先查用户信息，再去请求其他
    [self queryUserInfo];

    [self reqUnreadMsgCount];

    [self getYesProfitScore];
    [self reqCloudstorage];

    [self reqNewSystemMsg];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goRouterConfigView) name:kNOTIFICATION_UNCONFIG object:nil];
}

- (void)goToDeviceBingding
{
    WLRouterBingFlowController *flowController = [[WLRouterBingFlowController alloc] init];
    flowController.isPresented = YES;
    flowController.isPopDisabled = YES;
    flowController.isPopToMain = YES;
    flowController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:flowController animated:NO];
}
- (void)refreshInfomation
{
    [self getYesProfitScore];
    [self reqCloudstorage];
    [self reqBannerList];
    [self reqNewSystemMsg];
//    [self receiveRouterCloud];
}

- (void)userLoginedToRefresh
{
    [self reqUnreadMsgCount];
    
    [self getYesProfitScore];
    [self reqCloudstorage];
    [self reqNewSystemMsg];
//    [self receiveRouterCloud];
}

- (void)routerChangeToRefresh
{
    [self getYesProfitScore];
    [self reqCloudstorage];
//    [self receiveRouterCloud];
}

//- (void)goRouterConfigView
//{
//    WLRouterBingFlowController *flowController = [[WLRouterBingFlowController alloc] init];
//    flowController.flowStatus = 1;
//    flowController.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:flowController animated:NO];
//}

- (void)queryUserInfo
{
//    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/query" withParamsDic:nil success:^(NSDictionary *successDict) {
//        NSDictionary *dicto = successDict[@"object"][@"currentDevice"];
//        NSArray *arrKey = dicto.allKeys;
//        for (int i=0; i<arrKey.count; i++) {
//            NSString *key = arrKey[i];
//            WLLog(@"key:%@,value:%@,class:%@",key,dicto[key],[dicto[key] class]);
//        }
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        if ([[[WLUseManager shareUser] getUserInformation] devCount] == 0) {
            [self goToDeviceBingding];
            return;
        }
//        if (user.sord == nil) {
//            [weakSelf goRouterConfigView];
//        }
//        [weakSelf userLoginedToRefresh];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [WLCommonTool goToLogin];
    } error:^(NSError *error) {
        if (error.code != DoNotHaveNetCode) {
            [WLCommonTool goToLogin];
        }
    } inView:[UIApplication sharedApplication].keyWindow];
}

- (void)reqUnreadMsgCount
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/count/user" withParamsDic:nil success:^(NSDictionary *successDict) {
        NSInteger count = [successDict[@"count"] integerValue];
        if (count>0) {
            [weakSelf.tabBarController.tabBar showBadgeOnItemIndex:2];
            [[NSUserDefaults standardUserDefaults] setInteger:count forKey:UNREAD_MSG_NUM];
        }
        else
        {
            [weakSelf.tabBarController.tabBar hideBadgeOnItemIndex:2];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:UNREAD_MSG_NUM];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}

- (void)setupUI
{
    _cycleADView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, WLScaleX(160)) delegate:self placeholderImage:[UIImage imageNamed:@"placeHold_ad"]];
    
//    cycleADView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
//    cycleADView.titlesGroup = titles;
    _cycleADView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [_homeScroller addSubview:_cycleADView];
    
    _ivNotice = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(160+14), 16, 15)];
    _ivNotice.image = [UIImage imageNamed:@"sys_notice"];
    [_homeScroller addSubview:_ivNotice];
    _ivNotice.hidden = YES;
    _labNotice = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16+8)+16, CGRectGetMidY(_ivNotice.frame)-10, WIDTH_SCREEN_WL-WLScaleX(40)-16, 20)];
    _labNotice.font = [WLCommonTool fontTypePingFangSCRegular:11];
    _labNotice.textColor = wlDarkGrayColor;
    [_homeScroller addSubview:_labNotice];
    UIButton *btnNotice = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMinY(_labNotice.frame), WIDTH_SCREEN_WL-WLScaleX(32), 20)];
    [btnNotice addTarget:self action:@selector(noticeDetailAction) forControlEvents:UIControlEventTouchUpInside];
    [_homeScroller addSubview:btnNotice];
    
    UILabel *labProfit = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(17), WLScaleX(200), 120, 30)];
    labProfit.textColor = wlBlackColor;
    labProfit.font = [WLCommonTool fontTypePingFangSCMedium:20];//[UIFont systemFontOfSize:20];
    [_homeScroller addSubview:labProfit];
    NSMutableAttributedString *strProfit = [[NSMutableAttributedString alloc] initWithString:@"收益（昨日）"];
    [strProfit addAttribute:NSFontAttributeName
                      value:[WLCommonTool fontTypePingFangSCMedium:15]//[UIFont systemFontOfSize:15]
                      range:NSMakeRange(2, strProfit.length-2)];
    [strProfit addAttribute:NSForegroundColorAttributeName value:wlLightTextColor range:NSMakeRange(2,strProfit.length-2)];
    labProfit.attributedText = strProfit;
    
    UIView *vBackProfit = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(238), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(86))];//注意mask蒙版的位置
    [_homeScroller addSubview:vBackProfit];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = vBackProfit.bounds;  // 设置显示的frame
    gradientLayer.colors = @[(__bridge id)wlUIColorRGB(0x1A59E2).CGColor,(__bridge id)wlUIColorRGB(0x2292F5).CGColor]; // 设置渐变颜色
    //    gradientLayer.locations = @[@0.0, @0.2, @0.5];    // 颜色的起点位置，递增，并且数量跟颜色数量相等
    gradientLayer.startPoint = CGPointMake(0, 0);   //
    gradientLayer.endPoint = CGPointMake(1, 0);     //
    [vBackProfit.layer addSublayer:gradientLayer];
    
    vBackProfit.layer.cornerRadius = 5;//WLScaleX(5);
    vBackProfit.layer.masksToBounds = YES;
    
    UIButton *btnDetail = [[UIButton alloc] initWithFrame:vBackProfit.bounds];
    [btnDetail addTarget:self action:@selector(detailAction) forControlEvents:UIControlEventTouchUpInside];
    [vBackProfit addSubview:btnDetail];
    
    UILabel *labIntegral = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(24), WLScaleX(16), 60, 25)];
    labIntegral.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labIntegral.textColor = [UIColor whiteColor];
    labIntegral.text = @"i链积分:";
    [vBackProfit addSubview:labIntegral];
    
    labYesProfit = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(24), WLScaleX(16)+25, CGRectGetWidth(vBackProfit.bounds)-WLScaleX(48), 30)];
    labYesProfit.textColor = [UIColor whiteColor];
    labYesProfit.font = [WLCommonTool fontTypePingFangSCRegular:20];
    [vBackProfit addSubview:labYesProfit];
    
    UILabel *labCloud = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(17), CGRectGetMaxY(vBackProfit.frame)+WLScaleX(20), 100, 30)];
    labCloud.textColor = wlBlackColor;
    labCloud.font = [WLCommonTool fontTypePingFangSCMedium:20];//[UIFont systemFontOfSize:20];
    labCloud.text = @"云盘";
    [_homeScroller addSubview:labCloud];
    
    CGFloat vWidth = (WIDTH_SCREEN_WL-WLScaleX(42))/2.0;
    UIView *vPhoto = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(labCloud.frame)+WLScaleX(8), vWidth, WLScaleX(220))];
    vPhoto.layer.cornerRadius = 5;//WLScaleX(5);
    vPhoto.layer.masksToBounds = YES;
    vPhoto.layer.borderWidth = WLScaleX(1);
    vPhoto.layer.borderColor = wlBorderColor.CGColor;
    [_homeScroller addSubview:vPhoto];

    UIView *vPhotoTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vWidth, WLScaleX(160))];
    [vPhoto addSubview:vPhotoTop];
    CAGradientLayer *gradientPhotoTop = [CAGradientLayer layer];
    gradientPhotoTop.frame = vPhotoTop.bounds;  // 设置显示的frame
    gradientPhotoTop.colors = @[(__bridge id)wlUIColorRGB(0x2547F0).CGColor,(__bridge id)wlUIColorRGB(0x3B98FF).CGColor]; // 设置渐变颜色
    gradientPhotoTop.startPoint = CGPointMake(0, 0);
    gradientPhotoTop.endPoint = CGPointMake(1, 0);
    [vPhotoTop.layer addSublayer:gradientPhotoTop];
    
    UIButton *btnPhoto = [[UIButton alloc] initWithFrame:vPhoto.bounds];
    btnPhoto.tag = 0;
    [btnPhoto addTarget:self action:@selector(storageAction:) forControlEvents:UIControlEventTouchUpInside];
    [vPhoto addSubview:btnPhoto];
    
    UIImageView *ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(140)-31, 38, 31)];
    ivPhoto.image = [UIImage imageNamed:@"home_photo"];
    [vPhoto addSubview:ivPhoto];
    
    UIImageView *ivPhotoTip = [[UIImageView alloc] initWithFrame:CGRectMake(vWidth-52, 0, 52, 48)];
    ivPhotoTip.image = [UIImage imageNamed:@"home_photo_tip"];
    [vPhoto addSubview:ivPhotoTip];

    UILabel *labPhoto = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(170), 50, WLScaleX(40))];//160+10
    labPhoto.textColor = wlBlackColor;
    labPhoto.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labPhoto.text = @"照片";
    [vPhoto addSubview:labPhoto];
    
    labPhotoStorage = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+50, WLScaleX(170), vWidth-WLScaleX(32)-50, WLScaleX(40))];
    labPhotoStorage.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labPhotoStorage.textColor = wlLightTextColor;
    labPhotoStorage.textAlignment = NSTextAlignmentRight;
    [vPhoto addSubview:labPhotoStorage];
    
    //电影
    UIView *vMovie = [[UIView alloc] initWithFrame:CGRectMake(vWidth+WLScaleX(26), CGRectGetMinY(vPhoto.frame), vWidth, WLScaleX(110))];
    vMovie.layer.cornerRadius = WLScaleX(5);
    vMovie.layer.masksToBounds = YES;
    vMovie.layer.borderWidth = WLScaleX(1);
    vMovie.layer.borderColor = wlBorderColor.CGColor;
    [_homeScroller addSubview:vMovie];
    
    UIView *vMovieTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vWidth, WLScaleX(80))];
    [vMovie addSubview:vMovieTop];
    CAGradientLayer *gradientMovieTop = [CAGradientLayer layer];
    gradientMovieTop.frame = vMovieTop.bounds;  // 设置显示的frame
    gradientMovieTop.colors = @[(__bridge id)wlUIColorRGB(0x4549EC).CGColor,(__bridge id)wlUIColorRGB(0x6B95FF).CGColor]; // 设置渐变颜色
    gradientMovieTop.startPoint = CGPointMake(0, 0);
    gradientMovieTop.endPoint = CGPointMake(1, 0);
    [vMovieTop.layer addSublayer:gradientMovieTop];
    
    UIButton *btnVideo = [[UIButton alloc] initWithFrame:vMovie.bounds];
    btnVideo.tag = 1;
    [btnVideo addTarget:self action:@selector(storageAction:) forControlEvents:UIControlEventTouchUpInside];
    [vMovie addSubview:btnVideo];
    
    UIImageView *ivMovie = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(35), 31, 37)];
    ivMovie.image = [UIImage imageNamed:@"home_movie"];
    [vMovie addSubview:ivMovie];
    
    UIImageView *ivMovieTip = [[UIImageView alloc] initWithFrame:CGRectMake(vWidth-40, WLScaleX(2), 40, 46)];
    ivMovieTip.image = [UIImage imageNamed:@"home_movie_tip"];
    [vMovie addSubview:ivMovieTip];
    
    UILabel *labMovie = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(80), 40, WLScaleX(30))];
    labMovie.textColor = wlBlackColor;
    labMovie.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labMovie.text = @"视频";
    [vMovie addSubview:labMovie];
    
    labVideoStorage = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+50, WLScaleX(80), vWidth-WLScaleX(32)-50, WLScaleX(30))];
    labVideoStorage.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labVideoStorage.textColor = wlLightTextColor;
    labVideoStorage.textAlignment = NSTextAlignmentRight;
    [vMovie addSubview:labVideoStorage];
    /*
    //音乐
    UIView *vMusic = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(vPhoto.frame)+WLScaleX(10), vWidth, WLScaleX(100))];
    vMusic.layer.cornerRadius = 5;//WLScaleX(5);
    vMusic.layer.masksToBounds = YES;
    vMusic.layer.borderWidth = WLScaleX(1);
    vMusic.layer.borderColor = wlBorderColor.CGColor;
    [_homeScroller addSubview:vMusic];
    
    UIView *vMusicTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vWidth, WLScaleX(70))];
    [vMusic addSubview:vMusicTop];
    CAGradientLayer *gradientMusicTop = [CAGradientLayer layer];
    gradientMusicTop.frame = vMusicTop.bounds;  // 设置显示的frame
    gradientMusicTop.colors = @[(__bridge id)wlUIColorRGB(0x8530DD).CGColor,(__bridge id)wlUIColorRGB(0x9F6DFF).CGColor]; // 设置渐变颜色
    gradientMusicTop.startPoint = CGPointMake(0, 0);
    gradientMusicTop.endPoint = CGPointMake(1, 0);
    [vMusicTop.layer addSublayer:gradientMusicTop];
    
    UIButton *btnAudio = [[UIButton alloc] initWithFrame:vMusic.bounds];
    btnAudio.tag = 2;
    [btnAudio addTarget:self action:@selector(storageAction:) forControlEvents:UIControlEventTouchUpInside];
    [vMusic addSubview:btnAudio];
    
    UIImageView *ivMusic = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(30), 30, 30)];
    ivMusic.image = [UIImage imageNamed:@"home_music"];
    [vMusic addSubview:ivMusic];
    
    UIImageView *ivMusicTip = [[UIImageView alloc] initWithFrame:CGRectMake(vWidth-61, 0, 61, 42)];
    ivMusicTip.image = [UIImage imageNamed:@"home_music_tip"];
    [vMusic addSubview:ivMusicTip];
    
    UILabel *labMusic = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(70), 40, WLScaleX(30))];
    labMusic.textColor = wlBlackColor;
    labMusic.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labMusic.text = @"音乐";
    [vMusic addSubview:labMusic];
    
    labAudioStorage = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+50, WLScaleX(70), vWidth-WLScaleX(32)-50, WLScaleX(30))];
    labAudioStorage.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labAudioStorage.textColor = wlLightTextColor;
    labAudioStorage.textAlignment = NSTextAlignmentRight;
    [vMusic addSubview:labAudioStorage];
    */
    //空闲
    UIView *vFree = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(26)+vWidth, CGRectGetMaxY(vMovie.frame)+WLScaleX(10), vWidth, WLScaleX(100))];
    vFree.layer.cornerRadius = 5;//WLScaleX(5);
    vFree.layer.masksToBounds = YES;
    vFree.layer.borderWidth = WLScaleX(1);
    vFree.layer.borderColor = wlBorderColor.CGColor;
    [_homeScroller addSubview:vFree];
    
    UIView *vFreeTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vWidth, WLScaleX(70))];
    [vFree addSubview:vFreeTop];
    CAGradientLayer *gradientFreeTop = [CAGradientLayer layer];
    gradientFreeTop.frame = vFreeTop.bounds;  // 设置显示的frame
    gradientFreeTop.colors = @[(__bridge id)wlUIColorRGB(0xAAAAAA).CGColor,(__bridge id)wlUIColorRGB(0xCDCDCD).CGColor]; // 设置渐变颜色
    gradientFreeTop.startPoint = CGPointMake(0, 0);
    gradientFreeTop.endPoint = CGPointMake(1, 0);
    [vFreeTop.layer addSublayer:gradientFreeTop];
    
//    UIButton *btnFree = [[UIButton alloc] initWithFrame:vFree.bounds];
//    [btnFree addTarget:self action:@selector(freeAction) forControlEvents:UIControlEventTouchUpInside];
//    [vFree addSubview:btnFree];

    UIImageView *ivFree = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(30), 34, 28)];
    ivFree.image = [UIImage imageNamed:@"home_free"];
    [vFree addSubview:ivFree];
    UITapGestureRecognizer *tapGuesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGuestre)];
    [ivFree addGestureRecognizer:tapGuesture];
    
    UILabel *labFree = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(70), 40, WLScaleX(30))];
    labFree.textColor = wlBlackColor;
    labFree.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labFree.text = @"空闲";
    [vFree addSubview:labFree];
    
    labFreeStorage = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16)+50, WLScaleX(70), vWidth-WLScaleX(32)-50, WLScaleX(30))];
    labFreeStorage.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labFreeStorage.textColor = wlLightTextColor;
    labFreeStorage.textAlignment = NSTextAlignmentRight;
    [vFree addSubview:labFreeStorage];
}
- (void)tapGuestre {
    [self addTaskToCenterWihtModel];
}
#pragma mark - Banner
- (void)reqBannerList
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"banner/app/list" withParamsDic:nil success:^(NSDictionary *successDict) {
        NSArray *arrBanners = [WLBannerModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        weakSelf.bannerLists = arrBanners;
        [weakSelf setBannerDatasource];
        [weakSelf.homeScroller.mj_header endRefreshing];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf.homeScroller.mj_header endRefreshing];
//        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        [weakSelf.homeScroller.mj_header endRefreshing];
    } inView:nil];
}

- (void)setBannerDatasource
{
    NSMutableArray *arrImgs = [[NSMutableArray alloc] initWithCapacity:self.bannerLists.count];
    for (WLBannerModel *bannerModel in self.bannerLists) {
        [arrImgs addObject:bannerModel.imgPath];
    }
    _cycleADView.imageURLStringsGroup = arrImgs;
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    WLBannerModel *bannerModel = self.bannerLists[index];
    if (bannerModel.attribute1.length>5)
    {
        WLWebViewController *webView = [[WLWebViewController alloc] init];
        webView.urlStr = [NSString stringWithFormat:@"%@?userTag=%@",bannerModel.attribute1,[[WLUseManager shareUser] getUserRouterTag]];//bannerModel.attribute1;
        webView.titleStr = bannerModel.title;
        webView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webView animated:YES];
    }
}
- (void)reqNewSystemMsg
{
    WLWkSelf;
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/system/new" withParamsDic:nil success:^(NSDictionary *successDict) {
        WLMsgModel *msgModel = [WLMsgModel mj_objectWithKeyValues:successDict[@"object"]];
        weakSelf.ivNotice.hidden = NO;
        weakSelf.labNotice.text = msgModel.title;
        weakSelf.noticeModel = msgModel;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
        weakSelf.ivNotice.hidden = YES;
        weakSelf.labNotice.text = nil;
    } error:^(NSError *error) {
        
    } inView:nil];
}

- (void)noticeDetailAction
{
    if (_noticeModel==nil) {
        return;
    }
    if (_noticeModel.url.length>7)
    {
        WLWebViewController *webView = [[WLWebViewController alloc] init];
        webView.urlStr = _noticeModel.url;
        webView.titleStr = _noticeModel.title;
        webView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webView animated:YES];
    }
    else
    {
        WLMessageDetailController *msgDetailController = [[WLMessageDetailController alloc] init];
        msgDetailController.messageInfo = _noticeModel;
        msgDetailController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:msgDetailController animated:YES];
    }
}

#pragma mark - yesterday Score
- (void)getYesProfitScore
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"score/app/user/score/yes" withParamsDic:nil success:^(NSDictionary *successDict) {
//        NSDictionary *dict = successDict[@"object"];
//        if (dict != nil&&[dict isKindOfClass:[NSNull class]]==NO)
//        {
//            [weakSelf showYesGetScore:[NSString stringWithFormat:@"%@",strScore]];
//        }
        [weakSelf showYesGetScore:successDict[@"object"]];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
        [weakSelf showYesGetScore:nil];
    } error:^(NSError *error) {
        
    } inView:nil];
}
//{
//    id = 0;
//    modifyTime = 1537950160883;
//    rankType = 0;
//    score = 6500;
//    userId = 0;
//}

- (void)showYesGetScore:(NSDictionary *)dictScore
{
    if (dictScore != nil&&[dictScore isKindOfClass:[NSNull class]]==NO) {
        NSString *strScore = [NSString stringWithFormat:@"%@",dictScore[@"score"]];
        NSString *labStr = [NSString stringWithFormat:@"%@ ≈ %@元",strScore,dictScore[@"rmb"]];
        NSRange range = [strScore rangeOfString:@"."];
        if (range.location != NSNotFound) {
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:labStr];
            [attStr addAttribute:NSFontAttributeName
                               value:[WLCommonTool fontTypePingFangSCMedium:12]
                               range:NSMakeRange(range.location, attStr.length-range.location)];
            labYesProfit.attributedText = attStr;
        }
        else
        {
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:labStr];
            [attStr addAttribute:NSFontAttributeName
                           value:[WLCommonTool fontTypePingFangSCMedium:12]
                           range:NSMakeRange(strScore.length, attStr.length-strScore.length)];
            labYesProfit.attributedText = attStr;
        }
    }
    else
    {
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"0 ≈ 0元"];
        [attStr addAttribute:NSFontAttributeName
                       value:[WLCommonTool fontTypePingFangSCMedium:12]
                       range:NSMakeRange(1, attStr.length-1)];
        labYesProfit.attributedText = attStr;
    }
//    labYesProfit.text = score;
}

- (void)detailAction
{
    WLMyScoreProfitController *myScoreController = [[WLMyScoreProfitController alloc] init];
    myScoreController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:myScoreController animated:YES];
}

#pragma mark - cloud info



- (void)reqCloudstorage
{
    

//    if (![WLCommonTool isConnectedTianYiLian]) {
//        labPhotoStorage.text = @"";
//        labVideoStorage.text = @"";
//        //        labAudioStorage.text = @"";
//        labFreeStorage.text = @"";
//        return;
//    }
    WLWkSelf
    ///storage/device/c12478fa924e3371283f2b9a0bfc921a
    
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/storage", HTTP_HOST_ROUTER];
    } else {//http://router.skywindlink.com/router/storage/item/type/0/c12478fa924e3371283f2b9a0bfc921a
        url = [NSString stringWithFormat:@"%@/storage/device/%@", HTTP_HOST_WEB,[[WLUseManager shareUser] getUserCurrentRouter]];
    }
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        if (![successDict[@"object"] isKindOfClass:[NSNull class]]) {
            weakSelf.dictStorage = successDict[@"object"];
            [weakSelf updateCloudInfo];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"磁盘大小获取失败" delayTime:2.f];
    } inView:nil];
}
//object =     {
//    deviceId = 8972400904;
//    enable = 1;
//    id = 13;
//    modifyTime = 1538279085000;
//    movie = 1134;
//    music = "3.6";
//    other = 0;
//    photo = "2.2";
//    remark = "<null>";
//    total = 32768;
//    userId = 41;
//};

- (void)updateCloudInfo
{
    if (self.dictStorage != nil) {
        
        labPhotoStorage.text = [NSString formateSizeWithKBytes:[self.dictStorage[@"photo"] longLongValue] > 0 ? [self.dictStorage[@"photo"] longLongValue] :0];
        labVideoStorage.text = [NSString formateSizeWithKBytes:[self.dictStorage[@"movie"] longLongValue] > 0 ? [self.dictStorage[@"movie"] longLongValue] :0];
        labFreeStorage.text = [NSString formateSizeWithKBytes:[self.dictStorage[@"other"] longLongValue] > 0 ? [self.dictStorage[@"other"] longLongValue] :0];
    }
    else
    {
        labPhotoStorage.text = @"";
        labVideoStorage.text = @"";
//        labAudioStorage.text = @"";
        labFreeStorage.text = @"";
    }
}

- (void)receiveRouterCloud
{
    NSDictionary *dict = @{@"type":@"DEVICE_DISKGET_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    if ([msgModel.type isEqualToString:@"DEVICE_DISKGET_REP"]) {
        if (msgModel.content != nil) {
            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            if (dic !=nil) {
                self.dictStorage = dic;
                [self updateCloudInfo];
            }
        }
    }
}

- (void)addTaskToCenterWihtModel {
    
    WLFileUpDownLoadModel *model = [[WLFileUpDownLoadModel alloc] init];
    //    model.requestURL = selectModel.filePath;
    model.fileType = SPFileTypeVideo;
    model.loadState = FileLoadingStateWaiting;
    model.fileName = @"3.mp4";
    //    model.fileTotalBytes = [selectModel.fileSize longLongValue] * KB_UNIT;
    model.isUpLoad = NO;
    NSArray *tasksArr = @[model];
    [[WLDownLoadCenter shareInstance] addTasks:tasksArr];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:kUpDownloadTaskCompleteNofication object:nil];
}
- (void)storageAction:(UIButton *)btnStorage
{
#warning
//    if (![WLCommonTool isConnectedTianYiLian]) {
//        [WLCommonTool showAlrtToSettingWithTitle:@"请连接到您的天翼链路由器WiFi。" message:nil cancel:@"取消" confirmStr:@"连接"];
//        return;
//    }
    
    WLCloudController *cloudController = [[WLCloudController alloc] init];
    cloudController.index = btnStorage.tag;
    cloudController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cloudController animated:YES];
}

- (void)showGuideMaskView
{
    CGRect frame = [UIScreen mainScreen].bounds;
    UIView *bgView = [[UIView alloc]initWithFrame:frame];
    bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(maskTapClick:)];
//    [bgView addGestureRecognizer:tap];
    [self.tabBarController.view addSubview:bgView];
    
    CGRect rect = CGRectMake(0, WLScaleX(232), WIDTH_SCREEN_WL, WLScaleX(98));//vBackProfitf的位置
    CGRect cutRect = [_homeScroller convertRect:rect toView:bgView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIImageView *ivArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mask_arrow_ltop"]];
    ivArrow.center = CGPointMake(WIDTH_SCREEN_WL-WLScaleX(16)-178-17-10, CGRectGetMaxY(cutRect)+WLScaleX(10)+17);
    [bgView addSubview:ivArrow];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_first_text"]];
    ivText.center = CGPointMake(WIDTH_SCREEN_WL-WLScaleX(16)-89, CGRectGetMaxY(cutRect)+WLScaleX(10)+35);
    [bgView addSubview:ivText];
    
    UIButton *btnNext = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(18), 90, 30)];
    [btnNext setBackgroundImage:[UIImage imageNamed:@"mask_next_btn"] forState:UIControlStateNormal];
    [btnNext addTarget:self action:@selector(secondMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnNext];
    
//    CGFloat vWidth = (WIDTH_SCREEN_WL-WLScaleX(42))/2.0;
//    CGRect rectPhoto = CGRectMake(0, WLScaleX(238+86+20+2)+30, WIDTH_SCREEN_WL, WLScaleX(122));
//    CGRect rectBottom = CGRectMake(0, WLScaleX(238+86+20+2+122)+30, vWidth+WLScaleX(20), WLScaleX(110));
//    CGRect cutTopPart = [_homeScroller convertRect:rectPhoto toView:bgView];
//    CGRect cutBottomPart = [_homeScroller convertRect:rectBottom toView:bgView];
//
//    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
//    [path appendPath:[[UIBezierPath bezierPathWithRect:cutTopPart] bezierPathByReversingPath]];
//    [path appendPath:[[UIBezierPath bezierPathWithRect:cutBottomPart] bezierPathByReversingPath]];
//
//    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
//    shapeLayer.path = path.CGPath;
//    [bgView.layer setMask:shapeLayer];
    
    
//    CGRect rectBar = CGRectMake((WIDTH_SCREEN_WL-WLScaleX(70))/2.0, HEIGHT_SCREEN_WL-WL_TabBarHeight, WLScaleX(70), WL_TabBarHeight-WL_Bottom);
//
//    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
//    [path appendPath:[[UIBezierPath bezierPathWithRect:rectBar] bezierPathByReversingPath]];
//
//    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
//    shapeLayer.path = path.CGPath;
//    [bgView.layer setMask:shapeLayer];
}

- (void)secondMaskViewAction:(UIButton *)btnNext
{
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setInteger:1 forKey:@"maskGuideIndex"];
    UIView *bgView = btnNext.superview;
    
    NSArray *arrLayers = [NSArray arrayWithArray:bgView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    
    for (UIView *subView in bgView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    CGFloat vWidth = (WIDTH_SCREEN_WL-WLScaleX(42))/2.0;
    CGRect rectPhoto = CGRectMake(0, WLScaleX(238+86+20+2)+30, WIDTH_SCREEN_WL, WLScaleX(122));
    CGRect rectBottom = CGRectMake(0, WLScaleX(238+86+20+2+122)+30, vWidth+WLScaleX(20), WLScaleX(110));
    CGRect cutTopPart = [_homeScroller convertRect:rectPhoto toView:bgView];
    CGRect cutBottomPart = [_homeScroller convertRect:rectBottom toView:bgView];

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutTopPart] bezierPathByReversingPath]];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutBottomPart] bezierPathByReversingPath]];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(55), CGRectGetMinY(cutTopPart)-WLScaleX(10)-30, 90, 30)];
    [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_next_btn"] forState:UIControlStateNormal];
    [btnSecond addTarget:self action:@selector(thirdMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnSecond];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_second_text"]];
    ivText.center = CGPointMake(WLScaleX(55)+98, CGRectGetMinY(btnSecond.frame)-WLScaleX(12)-23);
    [bgView addSubview:ivText];
    
    UIImageView *ivArrow = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame)+135, CGRectGetMinY(ivText.frame)+32, 43, 35)];
    ivArrow.image = [UIImage imageNamed:@"mask_arrow_rbottom"];
    [bgView addSubview:ivArrow];
}

- (void)thirdMaskViewAction:(UIButton *)btnNext
{
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setInteger:2 forKey:@"maskGuideIndex"];
    UIView *bgView = btnNext.superview;
    
    NSArray *arrLayers = [NSArray arrayWithArray:bgView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    
    for (UIView *subView in bgView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    CGRect rectBar = CGRectMake((WIDTH_SCREEN_WL-WLScaleX(70))/2.0, HEIGHT_SCREEN_WL-WL_TabBarHeight, WLScaleX(70), WL_TabBarHeight-WL_Bottom);

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:rectBar] bezierPathByReversingPath]];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    float space = WIDTH_SCREEN_WL>320?5:20;
    UIImageView *ivArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_third_arrow"]];
    ivArrow.center = CGPointMake(WIDTH_SCREEN_WL/2.0-space, CGRectGetMinY(rectBar)-35);
    [bgView addSubview:ivArrow];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_third_text"]];
    ivText.center = CGPointMake(CGRectGetMaxX(ivArrow.frame)+80+5, CGRectGetMinY(ivArrow.frame)-15);
    [bgView addSubview:ivText];
    
    UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMinY(ivText.frame)-WLScaleX(12)-30, 90, 30)];
    [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_know_btn"] forState:UIControlStateNormal];
    [btnSecond addTarget:self action:@selector(homeMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnSecond];
}

- (void)homeMaskViewAction:(UIButton *)btnOver
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:1 forKey:@"maskGuideIndex"];
    UIView *view = btnOver.superview;
    [view removeFromSuperview];
}

- (void)maskTapClick:(UITapGestureRecognizer *)tap
{
    UIView *view = tap.view;
//    [shapeLayer removeFromSuperlayer];
//    tapFlag++;
//    if (tapFlag>=1)
    {
        [view removeFromSuperview];
        [view removeGestureRecognizer:tap];
        return;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
